package com.dd.cloud.user.mq;

import com.dd.cloud.user.service.sms.SmsUtils;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.Map;

/**
 * 短信队列消费者
 *
 * @author zk
 */
@Slf4j
@Component
public class SmsMessage {
    @Autowired
    private SmsUtils smsUtils;

    /**
     * 短信队列消费者
     *
     * @param channel
     * @param message
     * @param msg
     * @throws IOException
     */
    @RabbitHandler
    @RabbitListener(queues = MQConfig.SMS_QUERE)
    public void processHandler(Channel channel, Message message, Map<String, String> msg) throws IOException {
        try {
            if (CollectionUtils.isEmpty(msg)) {
                return;
            }
            String phone = msg.get("phone");
            if (StringUtils.isBlank(phone)) {
                return;
            }
            msg.remove("phone");
            smsUtils.sendSms(phone, msg);
            //手动确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            log.info("短信消息处理完");
        } catch (Exception e) {
            if (message.getMessageProperties().getRedelivered()) {
                log.error("短信消息已重复处理失败,拒绝再次接收...");
                // 拒绝消息
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
            } else {
                log.error("短信消息即将再次返回队列处理...");
            }
        }
    }
}
